package com.blogs.ui;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blogs.component.AuthorListAdapter;
import com.blogs.component.GetMoreListView;
import com.blogs.component.HomeAdapter;
import com.blogs.component.HomeBaseActivity;
import com.blogs.component.GetMoreListView.OnMoreListener;
import com.blogs.entity.AppEnums;
import com.blogs.entity.Author;
import com.blogs.entity.Feed;
import com.blogs.service.GetAuthorSearch;
import com.blogs.service.GetBlogSearch;
import com.blogs.tools.DBSharedPreferences;
import com.blogs.tools.LoadingGif;
import com.cnblogs.R;
import com.cnblogs.R.color;

public class SearchActivity extends HomeBaseActivity implements OnClickListener,OnItemClickListener{
	enum getDataMethod{
		search,//搜索
		more,//点击更多
	}//获取数据方式
	private DBSharedPreferences sp;
	private TextView title_include_title;
	
	private ArrayList<Feed> blogFeedList;
	private ArrayList<Author> authorFeedList;
	private ViewPager mPager;//页卡内容
	private List<View> listViews; // Tab页面列表
	private ImageView cursor;// 动画图片
	private TextView search_main_blog, search_main_author;// 页卡头标
	private int offset = 0;// 动画图片偏移量
	private int currIndex = 0;// 当前页卡编号
	private int bmpW;// 动画图片宽度
	
	private String blog_input_text;
	private String author_input_text;
	private int blogcurpage;
	private boolean blog_ismoreing=false;
	private GetMoreListView listViewBlog;
	private ListView listViewAuthor;
	private LoadingGif loadingGifBlog;
	private LoadingGif loadingGifAuthor;
	
	private View search_blog;
	private View search_author;
	private EditText search_blog_input;
	private EditText search_author_input;
	private Button search_blog_btn;
	private Button search_author_btn;
	private LinearLayout search_blog_list_body;
	private LinearLayout search_author_list_body;
	private LinearLayout search_titile_bg_ll;
	private RelativeLayout title_top_bg;
	
	private HomeAdapter blog_adapter;
	private AuthorListAdapter author_adapter;
	private InputMethodManager imm;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search_main);
		sp=new DBSharedPreferences(this);
		imm = (InputMethodManager)getSystemService(this.INPUT_METHOD_SERVICE);//软键盘
		ViewGroup headview=(ViewGroup)findViewById(R.id.main_title_include);
		title_include_title=(TextView)headview.findViewById(R.id.title_include_title);
		title_include_title.setText("搜索");
		search_main_blog = (TextView) findViewById(R.id.search_main_blog);
		search_main_author = (TextView) findViewById(R.id.search_main_author);
		mPager = (ViewPager) findViewById(R.id.vPager);
		cursor = (ImageView) findViewById(R.id.cursor);
		search_titile_bg_ll=(LinearLayout)findViewById(R.id.search_titile_bg_ll);
		title_top_bg=(RelativeLayout)headview;
		
		InitImageView();
		search_main_blog.setOnClickListener(new MyOnClickListener(0));
		search_main_author.setOnClickListener(new MyOnClickListener(1));
		InitViewPager();
		search_blog_input=(EditText)search_blog.findViewById(R.id.search_blog_input);
		search_blog_btn=(Button)search_blog.findViewById(R.id.search_blog_btn);
		search_blog_list_body=(LinearLayout)search_blog.findViewById(R.id.search_blog_list_body);
		search_blog_btn.setOnClickListener(this);
		
		search_author_input=(EditText)search_author.findViewById(R.id.search_author_input);
		search_author_btn=(Button)search_author.findViewById(R.id.search_author_btn);
		search_author_list_body=(LinearLayout)search_author.findViewById(R.id.search_author_list_body);
		search_author_btn.setOnClickListener(this);
		
		listViewBlog=new GetMoreListView(this);
		listViewBlog.setonMoreListener(new OnMoreListener() {
			
			public void onGetMore() {
				// TODO Auto-generated method stub
				if(!blog_ismoreing)
				{
					blog_ismoreing=true;
					GetMoreBlogData();
				}
			}
		});
		listViewBlog.setOnItemClickListener(this);
		loadingGifBlog=new LoadingGif(this, listViewBlog, search_blog_list_body,sp);
		loadingGifBlog.setOnReloadListener(new LoadingGif.OnReloadListener() {
			
			public void onClick() {
				// TODO Auto-generated method stub
				requestSearchBlogData();
			}
		});
		
		
		listViewAuthor=new ListView(this);
		listViewAuthor.setCacheColorHint(Color.TRANSPARENT);
		listViewAuthor.setOnItemClickListener(this);
		listViewAuthor.setDivider(getResources().getDrawable(R.drawable.line_01));
		loadingGifAuthor=new LoadingGif(this, listViewAuthor, search_author_list_body,sp);
		loadingGifAuthor.setOnReloadListener(new LoadingGif.OnReloadListener() {
			
			public void onClick() {
				// TODO Auto-generated method stub
				requestAuthorData();
			}
		});
		
		
		InitSkin();
		
	}
	private void InitSkin()
	{
		if(sp.GetIsDarkState())
		{
			cursor.getDrawable().setLevel(2);
			search_titile_bg_ll.getBackground().setLevel(2);
			mPager.getBackground().setLevel(2);
			title_top_bg.getBackground().setLevel(2);
			search_blog_input.getBackground().setLevel(2);
			search_author_input.getBackground().setLevel(2);
			search_blog_input.setTextColor(getResources().getColor(color.con_text_night));
			search_author_input.setTextColor(getResources().getColor(color.con_text_night));
		}
		else
		{
			cursor.getDrawable().setLevel(1);
			search_titile_bg_ll.getBackground().setLevel(1);
			mPager.getBackground().setLevel(1);
			title_top_bg.getBackground().setLevel(1);
			search_blog_input.getBackground().setLevel(1);
			search_author_input.getBackground().setLevel(1);
			search_blog_input.setTextColor(getResources().getColor(color.con_text_light));
			search_author_input.setTextColor(getResources().getColor(color.con_text_light));
		}
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		InitSkin();
		if(blog_adapter!=null)
		{
			blog_adapter.notifyDataSetChanged();
		}
		if(author_adapter!=null)
		{
			author_adapter.notifyDataSetChanged();
		}
	}
	/**
	 * 初始化ViewPager
	 */
	private void InitViewPager() {
		listViews = new ArrayList<View>();
		LayoutInflater mInflater = getLayoutInflater();
		search_blog=mInflater.inflate(R.layout.search_blog, null);
		search_author=mInflater.inflate(R.layout.search_author, null);
		listViews.add(search_blog);
		listViews.add(search_author);
		mPager.setAdapter(new MyPagerAdapter(listViews));
		mPager.setCurrentItem(0);
		mPager.setOnPageChangeListener(new MyOnPageChangeListener());
	}

	/**
	 * 初始化动画
	 */
	private void InitImageView() {
		bmpW = BitmapFactory.decodeResource(getResources(), R.drawable.view_page_b)
				.getWidth();// 获取图片宽度
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		int screenW = dm.widthPixels;// 获取分辨率宽度
		offset = (screenW / 2 - bmpW) / 2;// 计算偏移量
		Matrix matrix = new Matrix();
		matrix.postTranslate(offset, 0);
		cursor.setImageMatrix(matrix);// 设置动画初始位置
	}
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if(v==search_blog_btn&&!search_blog_input.getText().toString().trim().equals(""))
		{
			blog_input_text=search_blog_input.getText().toString();
			this.requestSearchBlogData();
            //隐藏软键盘
            imm.hideSoftInputFromWindow(search_blog_input.getWindowToken(), 0);

		}
		else if(v==search_author_btn&&!search_author_input.getText().toString().trim().equals(""))
		{
			author_input_text=search_author_input.getText().toString();
			this.requestAuthorData();
			//隐藏软键盘
            imm.hideSoftInputFromWindow(search_author_input.getWindowToken(), 0);
		}
	}
	private void requestSearchBlogData()
	{
		blogcurpage=1;
		loadingGifBlog.showLoading();
		this.sendBlogTimeLine(getDataMethod.search);
	}
	private void updateRequestBlogData(getDataMethod gdm)
	{
		if(blog_adapter!=null)
		{
			blog_adapter.notifyDataSetChanged();
			if(gdm==getDataMethod.search)
			{
				listViewBlog.setAdapter(blog_adapter);
			}
		}
		else
		{
			blog_adapter=new HomeAdapter(this, blogFeedList);
			listViewBlog.setAdapter(blog_adapter);
		}
		listViewBlog.onMoreComplete();
		loadingGifBlog.showData();
	}
	private void GetMoreBlogData()
	{
		blogcurpage++;
		this.sendBlogTimeLine(getDataMethod.more);
	}
	private void sendBlogTimeLine(final getDataMethod gdm)
	{
		new GetBlogSearch(blogcurpage, blog_input_text,new GetBlogSearch.IMsgCallBack() {
			
			public void onSuccess(ArrayList<Feed> feeds) {
				// TODO Auto-generated method stub
				if(blogFeedList==null)
					blogFeedList=new ArrayList<Feed>();
				if(gdm==getDataMethod.search)
				{
					blogFeedList.clear();
				}
				for(int i=0;i<feeds.size();i++)
				{
					blogFeedList.add(feeds.get(i));
				}
				if(gdm==getDataMethod.more)
				{
					blog_ismoreing=false;
					listViewBlog.onMoreComplete();
				}
				updateRequestBlogData(gdm);
			}
			
			public void onFailed() {
				// TODO Auto-generated method stub
				loadingGifBlog.showFiale();
			}
		}).loadData();
	}
	private void requestAuthorData()
	{
		loadingGifAuthor.showLoading();
		this.sendAuthorTimeLine();
	}
	private void updateRequestAuthorData()
	{
		if(author_adapter!=null)
		{
			author_adapter.notifyDataSetChanged();
		}
		else
		{
			author_adapter=new AuthorListAdapter(this, authorFeedList);
			listViewAuthor.setAdapter(author_adapter);
		}
		loadingGifAuthor.showData();
	}
	private void sendAuthorTimeLine()
	{
		new GetAuthorSearch(author_input_text, new GetAuthorSearch.IMsgCallBack() {
			
			public void onSuccess(ArrayList<Author> feedList) {
				// TODO Auto-generated method stub
				if(authorFeedList==null)
					authorFeedList=new ArrayList<Author>();
				authorFeedList.clear();
				for(int i=0;i<feedList.size();i++)
				{
					authorFeedList.add(feedList.get(i));
				}

				updateRequestAuthorData();
			}
			
			public void onFailed() {
				// TODO Auto-generated method stub
				loadingGifAuthor.showFiale();
			}
		}).loadData();
	}
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if(parent==listViewBlog)
		{
			if(position>blogFeedList.size())
				return;
			Intent intent=new Intent();
			intent.setClass(this, ContentActivity.class);
			intent.putExtra("Id", blogFeedList.get(position).blog_id);
			intent.putExtra("Title", blogFeedList.get(position).title);
			intent.putExtra("Author", blogFeedList.get(position).author);
			intent.putExtra("publicDate", blogFeedList.get(position).public_time);
			intent.putExtra("ViewCount", blogFeedList.get(position).hit);
			intent.putExtra("CommentCount", blogFeedList.get(position).comment);
			intent.putExtra("url", blogFeedList.get(position).blog_url);
			intent.putExtra("type",AppEnums.EnumContentType.search_blog_detail);
			startActivity(intent);
		}
		else if(parent==listViewAuthor)
		{
			if(position>authorFeedList.size())
				return;
			Intent intent=new Intent();
			intent.setClass(this, AuthorHomePage.class);
			intent.putExtra("avatar", authorFeedList.get(position).avatar);
			intent.putExtra("blogapp", authorFeedList.get(position).blogapp);
			intent.putExtra("name", authorFeedList.get(position).name);
			intent.putExtra("postcount", authorFeedList.get(position).postcount);
			intent.putExtra("updated", authorFeedList.get(position).updated);
			startActivity(intent);
		}
	}
	/**
	 * ViewPager适配器
	 */
	public class MyPagerAdapter extends PagerAdapter {
		public List<View> mListViews;

		public MyPagerAdapter(List<View> mListViews) {
			this.mListViews = mListViews;
		}

		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {
			((ViewPager) arg0).removeView(mListViews.get(arg1));
		}

		@Override
		public void finishUpdate(View arg0) {
		}

		@Override
		public int getCount() {
			return mListViews.size();
		}

		@Override
		public Object instantiateItem(View arg0, int arg1) {
			((ViewPager) arg0).addView(mListViews.get(arg1), 0);
			return mListViews.get(arg1);
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == (arg1);
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {
		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View arg0) {
		}
	}

	/**
	 * 头标点击监听
	 */
	public class MyOnClickListener implements View.OnClickListener {
		private int index = 0;

		public MyOnClickListener(int i) {
			index = i;
		}

		public void onClick(View v) {
			mPager.setCurrentItem(index);
		}
	};

	/**
	 * 页卡切换监听
	 */
	public class MyOnPageChangeListener implements OnPageChangeListener {

		int one = offset * 2 + bmpW;// 页卡1 -> 页卡2 偏移量

		public void onPageSelected(int arg0) {
			Animation animation = null;
			switch (arg0) {
			case 0:
				if (currIndex == 1) {
					search_main_blog.setTextColor(Color.parseColor("#669900"));
					search_main_author.setTextColor(Color.parseColor("#81A2C2"));
					animation = new TranslateAnimation(one, 0, 0, 0);
				} 
				break;
			case 1:
				if (currIndex == 0) {
					search_main_blog.setTextColor(Color.parseColor("#81A2C2"));
					search_main_author.setTextColor(Color.parseColor("#669900"));
					animation = new TranslateAnimation(offset, one, 0, 0);
				} 
				break;
			}
			currIndex = arg0;
			animation.setFillAfter(true);// True:图片停在动画结束位置
			animation.setDuration(300);
			cursor.startAnimation(animation);
		}

		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		public void onPageScrollStateChanged(int arg0) {
		}
	}
}
